package ha.web.servlet.game;

import ha.web.database.UserId;
import ha.web.games_manager.GM;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Servlet implementation class GamePage
 */
@WebServlet("/GamePage")
public class GamePage extends HttpServlet {
	private static final long serialVersionUID = 1L;
      
	
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GamePage() {
        super();
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		ServletContext context = getServletContext();
  	  	RequestDispatcher dispatcher = context.getRequestDispatcher("/Login");
  	  	dispatcher.forward(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
      int userId = -1;
      boolean cookieFound = false;
	  Cookie[] userCookie = request.getCookies();
	  for(int i=0; i<userCookie.length; i++) {
	      if ("chinese_checkers".equals(userCookie[i].getName())) {
	    	  String[] cookie = userCookie[i].getValue().split(":");
	    	  userId = Integer.parseInt(cookie[1]);
	    	  cookieFound = true;
	      }
	  }
	  if(!cookieFound)
		  return; //TODO
	  GM ins = GM.getInstance();
	  if (ins.IsUserAtDB(userId)) {
	      //check if user have a game - if so - load it
	      //if no - check waiting list
		  //TODO to change
		  int gameId = ins.get_game_id(userId);
			  List<String> players = ins.get_players(gameId);
			  DrawGame(request, response, 
					  players.get(0), players.get(1),ins.getPlayerById(userId).getName() ,ins.getPlayerTurnByGameId(gameId)); //TODO
      }else {
    	  ServletContext context = getServletContext();
    	  RequestDispatcher dispatcher = context.getRequestDispatcher("/Login");
    	  dispatcher.forward(request, response);
  		}
	  }
	
	protected void DrawGame(HttpServletRequest request, HttpServletResponse response, String p1, String p2,String userName,String playerTurn) throws IOException {
		//TODO - handle players turns
		PrintWriter out = response.getWriter();
		out.print("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">");
		out.print("<HTML><HEAD><TITLE>game page</TITLE>");
		out.print("<META http-equiv=Content-Type content=\"text/html\">");
		out.print("<link rel=\"stylesheet\" type=\"text/css\" href=\"gameDesign.css\" />");
		out.print("</HEAD><BODY><P>");
		out.print("<div align=\"center\">");
		out.print("<h1>2P chinese checkers</h1>");		
		out.print("<h3 style=\"color:#000F0F\">You are logged in as: " + userName + "</h3>");
		if(userName.equals(playerTurn)){
			out.print("<h3 style=\"color:#0000FF\" id=\"cturn\">Current turn: " + (userName.equals(playerTurn)?"It is your turn":playerTurn )+ "</h3>");
			out.print("<script>turn_ended=false</script>");
			out.print("<script>player=\"firstP\"</script>");
			out.print("<script>otherPlayer=\"secondP\"</script>");
		} else { 
			out.print("<h3 style=\"color:#FFFF00\" id=\"cturn\">Current turn: " + (userName.equals(playerTurn)?"It is your turn":playerTurn )+ "</h3>");
			out.print("<script>turn_ended=true</script>");
			out.print("<script>player=\"secondP\"</script>");
			out.print("<script>otherPlayer=\"firstP\"</script>");
		}
		
		out.print("<h3 id =turn_status></h3>");
		out.print("<table><tr>");
		out.print("<td><div id=\"boardplace\" align=\"center\"></div>");
		out.print("<br><button type=\"button\" class=\"button\" onclick=player_resign()>Resign</button>");
		out.print("<br><button type=\"button\" class=\"button\" onclick=get_statistics()>show statistics (test only!)</button>");
		out.print("</td>");
		out.print("<td valign=\"baseline\" width=\"200\"><u>CHAT</u><br>");
		out.print("<p align=\"right\">");
		out.print("<textarea disabled rows=\"25\" id=\"chat_window\" cols=\"25\"></textarea>");
		out.print("<input type=\"text\" name=\"chat\" id =\"chat_new_line\" size=\"27\"></input>");
		out.print("<input type=\"submit\" onclick=submit_chat(document.getElementById(\"chat_new_line\").value) class=\"button\" value=\"submit line\">");
		out.print("</p>");
		out.print("<div id=\"chatplace\" align=\"center\"></div></td>");
		out.print("</tr>");
		out.print("list of moves: <input type=\"text\" name=\"moves\" id =\"moves\" size=\"80\"></input>");
		out.print("<input type=\"submit\" id=\"s_moves\" onclick=submit_move() class=\"button\" value=\"End turn\">");
		out.print("<br><button type=\"button\" class=\"button\" onclick=game_rules()>game rules</button>");
//		out.print("<script>addLoadEvent(updateBoard())</script>");
		out.print("<script src=\"game_window.js\" type=\"text/javascript\"></script>");
		out.print("<p id =\"alerts\"></p>");
		out.print("<P></P>");
		out.print("</div>");
		out.print("</BODY></HTML>");

	}
}
